package com.rocksea.checkservice;


import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;



public class MainActivity extends AppCompatActivity implements
        android.app.LoaderManager.LoaderCallbacks<ArrayList<ServiceInfo>>,
        SearchView.OnQueryTextListener
{
    private static final int LOAD_HISTORY_ID = 1;
    private RecyclerView mListView;
    private ArrayList<ServiceInfo> mServiceInfos;
    private CheckThread thread;
    private ProgressDialog dialog;

    private String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };
    private static final int REQUEST_CODE = 0;
    private ContactAdapter adapter;
    private SideBar mSideBar;
    private CustomItemDecoration decoration;
    private LinearLayoutManager layoutManager;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        mListView = (RecyclerView) findViewById(R.id.rl_recycle_view);

        mSideBar = (SideBar) findViewById(R.id.side_bar);
        layoutManager = new LinearLayoutManager(this);
        mListView.setLayoutManager(layoutManager);
        decoration = new CustomItemDecoration(this);
        mListView.addItemDecoration(decoration);
        adapter = new ContactAdapter(this);
        mListView.setAdapter(adapter);
        mSideBar.setIndexChangeListener(new SideBar.indexChangeListener() {
            @Override
            public void indexChanged(String tag) {
                if (TextUtils.isEmpty(tag) || mServiceInfos.size() <= 0) return;
                for (int i = 0; i < mServiceInfos.size(); i++) {
                    if (tag.equals(mServiceInfos.get(i).getIndexTag())) {
                        layoutManager.scrollToPositionWithOffset(i, 0);
//                        layoutManager.scrollToPosition(i);
                        return;
                    }
                }
            }
        });

        PermissionsActivity.setOnPermissionsGrantedCallBack(onPermissionsGrantedCallBack);
        PermissionsChecker checker = new PermissionsChecker(this);
        if (!checker.lacksPermissions(permissions)) {
            Log.d("PermissionsChecker: ","权限已获取");
            DBManger.init(this);
            initData();
        }else {
            PermissionsActivity.startActivityForResult(this,REQUEST_CODE,permissions);
        }
    }



    private void initData()
    {
        getLoaderManager().initLoader(LOAD_HISTORY_ID,null,this);
    }
    private PermissionsActivity.OnPermissionsGrantedCallBack onPermissionsGrantedCallBack = new PermissionsActivity.OnPermissionsGrantedCallBack() {
        @Override
        public void onPermissionsGrantedCallBack()
        {
            Log.d("权限回调","onPermissionsGrantedCallBack: ");
            //权限获取成功，初始化数据库
            DBManger.init(MainActivity.this);
        }
    };

    @Override
    public android.content.Loader<ArrayList<ServiceInfo>> onCreateLoader(int id, Bundle args) {
        return new ServiceTask(getBaseContext());
    }

    @Override
    public void onLoadFinished(android.content.Loader<ArrayList<ServiceInfo>> loader, ArrayList<ServiceInfo> data)
    {
        mServiceInfos = data;
        Util.sortData(data);
        String tagStr = Util.getTags(mServiceInfos);
        mSideBar.setIndexStr(tagStr);
        decoration.setDatas(mServiceInfos,tagStr);
        adapter.addAll(mServiceInfos);
    }

    @Override
    public void onLoaderReset(android.content.Loader<ArrayList<ServiceInfo>> loader) {

    }

    private ListView.OnItemClickListener clickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            ServiceInfo mInfo = mServiceInfos.get(position);
            String url = String.format("%s:%s",mInfo.getServerIp(),mInfo.getDtuPort());
            Log.d("onItemClick: ",url);
            if (thread!=null)
            {
                thread.exit();
                thread =null;
            }
            thread = new CheckThread(mInfo.getServerIp(),Integer.parseInt(mInfo.getDtuPort()),handler);
            thread.start();
            dialog = ProgressDialog.show(MainActivity.this,"提示",String.format("正在尝试连接 %s",mInfo.getRegionName()),true,true,onCancelListener);
            dialog.show();
        }
    };

    private ProgressDialog.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            thread.exit();

        }
    };

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg)
        {
            dialog.dismiss();
            switch (msg.what){
                case UDPPackage.OFF_LINE:
                    Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                    thread.exit();
                    break;
                case UDPPackage.ON_LINE:
                    Toast.makeText(MainActivity.this, "连接服务器成功", Toast.LENGTH_SHORT).show();
                    thread.exit();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        MenuItem menuItem=menu.findItem(R.id.search);//
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setOnQueryTextListener(this);        //为搜索框设置监听事件
        searchView.setSubmitButtonEnabled(true);        //设置是否显示搜索按钮
        searchView.setQueryHint("输入服务器名称");        //设置提示信息
        searchView.setIconifiedByDefault(true);         //设置搜索默认为图标
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText)
    {
        adapter.cear();
        ArrayList<ServiceInfo> mServiceLists = new ArrayList<>();
        for (int i = 0; i < mServiceInfos.size(); i++) {
            if (mServiceInfos.get(i).getRegionName().contains(newText)){
                mServiceLists.add(mServiceInfos.get(i));
            }
        }
        adapter.addAll(mServiceLists);
        return true;
    }
}
